<!-- 分类list -->
<template>
  <div class="category-list">
    <van-nav-bar title="分类" />
    <van-row>
      <van-col span="6">
        <ul class="left-nav">
          <li
            v-for="(item, index) in categoryList"
            :key="index"
            :class="{categoryActive: categoryIndex === index}"
            @click="clickCategory(index, item.ID)"
          >
            {{ item.MALL_CATEGORY_NAME }}
            </li>
        </ul>
      </van-col>
      <van-col span="18">
        <div class="tabCategorySub">
          <van-tabs v-model="subActive" @click="clickCatgorySub">
            <van-tab
              v-for="(item, index) in categorySubList"
              :key="index"
              :title="item.MALL_SUB_NAME"
            ></van-tab>
          </van-tabs>
        </div>
        <!-- 上拉加载，下拉刷新 -->
        <div class="list-div">
          <van-pull-refresh v-model="isRefresh" @refresh="onRefresh">
            <van-list
              v-model="loading"
              :finished="finished"
              @load="onLoad"
            >
              <div class="list-item" v-for="(item, index) in goodsList" :key="index" @click="goGoodsInfo(item.ID)">
                <div class="list-item-img">
                  <img :src="item.IMAGE1" width="100%" onerror="this.src='http://cs-static-assets.oss-cn-beijing.aliyuncs.com/ds_system/errorimg.png'" />
                </div>
                <div class="list-item-text">
                    <div>{{item.NAME}}</div>
                    <div>￥{{item.ORI_PRICE | toMoney}}</div>
                </div>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import axios from 'axios';
import { Toast } from 'vant';
import requestUrl from "../../serverApi";
import toMoney from '../../filter/moneyFilter';
import Bus from '../../bus';
export default {
  data() {
    return {
      categoryList: [],
      categorySubList: [],
      categoryIndex: 0,
      subActive: 0,
      loading: false,
      finished: false,
      isRefresh: false,
      currPage: 1,
      goodsList: [],
      categorySubId: '',
    }
  },
  methods: {
    initialData() {
      this.isRefresh = false;
      this.finished = false;
      this.currPage = 1;
      this.goodsList = [];
      this.loading = false;
    },
    getCategoryList() {
      axios.get(requestUrl.getCategory).then(res => {
        const data = res.data;
        if (data.code === 200 && data.message) {
          this.categoryList = data.message;
          const { categoryId } = this.$route.query;
          let paramsId;
          if (categoryId === '-1') {
            // 点击tabbar进来的
            paramsId = this.categoryList[0].ID;
            this.categoryIndex = 0;
          } else {
            //  点击首页分类进来的
            paramsId = categoryId;
            this.categoryIndex = this.categoryList.findIndex(item => item.ID === categoryId);
          }
          this.getCategorySubList(paramsId); 
        }
      }).catch(err => {
        Toast.fail('获取大类数据失败');
      })
    },
    async clickCategory(index, categoryId) {
      // 点击大类,使用自执行函数解决异步的问题
      this.categoryIndex = index;
      await this.getCategorySubList(categoryId);
      this.initialData();
      this.loading = true;
      this.categorySubId = this.categorySubList[0].ID;
      this.onLoad();
    },
    getCategorySubList(categoryId) {
      // 根据大类获取小类
      const subUrl = `${requestUrl.getCategorySub}?categoryId=${categoryId}`;
      return new Promise((resolve, reject) => {
        axios.get(subUrl).then(res => {
          const data = res.data;
          if (data.code === 200 && data.message) {
            this.categorySubList = data.message;
            this.subActive = 0;
            resolve(); // 使用promise一定要加上resolve,否则使用await不生效
          }
        }).catch(err => {
          Toast.fail('获取小类数据失败');
          reject(err);
        })
      })
    },
    getGoodsList() {
      // 根据小类获取具体商品（分页）
      const subGoodsUrl = `${requestUrl.getSubGoods}?currPage=${this.currPage}&subId=${this.categorySubId}`;
      axios.get(subGoodsUrl).then((result) => {
        const data = result.data;
        // 这里一定要加length，否则会一直请求接口
        if (data.code === 200 && data.message.length) {
          this.currPage ++;
          this.goodsList = this.goodsList.concat(data.message);
        } else {
          this.finished = true;
        }
        this.loading = false;
      }).catch((err) => {
        this.loading = false;
        this.finished = true;
        Toast.fail('获取商品失败');
      });
    },
    clickCatgorySub(index, title) {
      // 点击tabs
      this.categorySubId = this.categorySubList[index].ID;
      this.initialData();
      this.loading = true;
      this.onLoad();
    },
    goGoodsInfo(id) {
      // url上传递参数最好还是使用query传递，使用parmas没成功（params->name）、（query-》path/name）
      this.$router.push({
        name: 'GoodsDetail',
        query: {
          goodsId: id,
        },
      })
    },
    onLoad() {
      // 异步问题（onLoad会在created后执行）
      const getId = setTimeout(() => {
        this.categorySubId = this.categorySubId || (this.categorySubList[0] || {}).ID;
        if (this.categorySubId) {
          this.getGoodsList();
          clearTimeout(getId);
        }
      }, 1000);
    },
    onRefresh() {
      setTimeout(() => {
        this.initialData();
        this.onLoad();
      }, 1000);
    },
  },
  mounted() {
    const clientHeight = document.documentElement.clientHeight;
    const leftNav = document.getElementsByClassName('left-nav')[0];
    const listDiv = document.getElementsByClassName('list-div')[0];
    leftNav.style.height = clientHeight - 46 - 50 + 'px';
    listDiv.style.height = clientHeight - 90 - 50 +'px';
  },
  created() {
    this.getCategoryList();
  },
  filters: {
    toMoney(value) {
      return toMoney(value);
    }
  },
};
</script>

<style scoped>
  .left-nav {
    background-color: #e4e7ed;
  }
  .left-nav > li {
    line-height: 43px;
    border-bottom: 1px solid #e4e7ed;
    padding: 0 3px;
    text-align: center;
    font-size: .8rem;
  }
  .categoryActive {
    background-color: #fff;
  }
  .list-div {
    overflow: auto;
  }
  .list-item{
    display: flex;
    flex-direction: row;
    font-size: 0.8rem;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fff;
    padding: 5px;
  }
  .list-item-img{
    flex: 8;
  }
  .list-item-text{
    flex:16;
    margin-top: 10px;
    margin-left: 10px;
  }
</style>